package overun.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import overun.pojo.User;
import overun.service.ValueSetService;
import overun.utils.EasyExcelUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName: excel
 * @Description:
 * @author: zhangPY
 * @version: V1.0
 * @date: 2019/4/10 17:15
 */
@Controller
@Api(value = "导入导出类")
public class ExeclController {

    @Resource
    private ValueSetService valueSetService;

    @RequestMapping(value = "import")
    @ApiOperation("导入数据")
    public void importExcel(MultipartFile file) throws Exception{

        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<User> lst = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    .head(User.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                    .doReadSync(); //开始读Excel，返回一个List<T>集合，继续后续入库操作

            //模拟导入数据库操作
            for (User userDO:lst){
                System.out.println(userDO.toString());
            }
            System.out.println(lst.size());
        }catch (IOException exception){
            throw new  RuntimeException(exception);
        }
    }



    @RequestMapping(value = "export")
    @ApiOperation("导出数据")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception{

        OutputStream outputStream=response.getOutputStream();

        /** 导出的数据 */
        List list = new ArrayList<User>();
        for (int i = 0 ; i< 12 ; i++) {
            User user = new User();
            user.setEmail(UUID.randomUUID().toString());
            user.setNickname(UUID.randomUUID().toString());
            user.setGender(String.valueOf(i%2));
            list.add(user);
        }

        /** 导出文件名 */
        String fileName = "测试报表.xls";

        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                // 针对IE或者以IE为内核的浏览器：
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName + System.currentTimeMillis() + ".xlsx"));
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", -1);
            response.setCharacterEncoding("UTF-8");

            EasyExcel.write(outputStream,User.class)//对应的导出实体类
                    .excelType(ExcelTypeEnum.XLSX)//excel文件类型，包括CSV、XLS、XLSX
                    .sheet("用户列表")//导出sheet页名称
                    .doWrite(list); //查询获取的数据集合List<T>，转成excel

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            outputStream.close();
        }

    }



    @RequestMapping(value = "downTemp")
    @ApiOperation("下载模板")
    public void downTemp(HttpServletRequest request, HttpServletResponse response) throws Exception{

        /** 导出文件名 */
        String fileName = "测试报表.xls";

        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName + System.currentTimeMillis() + ".xlsx"));
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", -1);
            response.setCharacterEncoding("UTF-8");

            valueSetService.getValueByKeyWord("");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet = EasyExcelUtil.writeSelectedSheet(User.class, 0, "测试报表");

            excelWriter.write(new ArrayList<String>(), writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
